package com.novellotus.iov.carvice.model;

import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.PersonalActivity;
import com.novellotus.iov.carvice.bean.CityBean;
import com.novellotus.iov.carvice.bean.PersonBean;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.GetJsonDataUtil;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;

import org.json.JSONArray;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;


/**
 * Created by Rich on 2017/7/31.
 */

public class PersonalModel {

    private PersonalActivity activity;
    private PersonInterface personInterface;
    private boolean first = true;
    private ArrayList<CityBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> CodeList = new ArrayList<>();

    public PersonalModel(PersonalActivity activity, PersonInterface personInterface) {
        this.activity = activity;
        this.personInterface = personInterface;
    }

    /**
     * 设置昵称编辑框
     */
    public void setNameEdit(final EditText edit, final Button button) {
        RxTextView.textChanges(edit)
                .compose(RxSchedulers.<CharSequence>lifecycle(activity))
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence value) {
                        super.onNext(value);
                        if (value.length() >= 1) {
                            if (!activity.code.equals("")) {
                                button.setClickable(true);
                                button.setTextColor(activity.getResources().getColorStateList(R.color.white));
                            } else {
                                button.setClickable(false);
                                button.setTextColor(activity.getResources().getColor(R.color.gray_line));
                            }
                            edit.setTextColor(activity.getResources().getColor(R.color.text_black));
                        } else {
                            edit.setTextColor(activity.getResources().getColor(R.color.textTipsRed));
                        }
                    }
                });
    }

    /**
     * 获取个人信息
     */
    public void getPersonalData() {
        Observable<BaseEntity<PersonBean>> observable = RetrofitFactory.getInstance().profile(SharedPreferencesUtils.getKey(activity)[0]);
        observable.compose(RxSchedulers.<BaseEntity<PersonBean>>lifecycle(activity))
                .compose(RxSchedulers.<BaseEntity<PersonBean>>compose())
                .subscribe(new BaseObserver<PersonBean>(activity) {
                    @Override
                    public void onSuccess(PersonBean response) {
                        personInterface.setMessage(response);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        personInterface.getMessageFail(msg);
                    }

                    @Override
                    public void onError(String msg) {
                        personInterface.getMessageFail(msg);
                    }
                });
    }


    public void showCityPicker(final TextView tv_area) {

        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                if (first) {
                    String JsonData = new GetJsonDataUtil().getJson(activity, "City.json");//获取assets目录下的json文件数据
                    ArrayList<CityBean> jsonBean = parseData(JsonData);//用Gson 转成实体
                    /**
                     * 添加省份数据
                     *
                     * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
                     * PickerView会通过getPickerViewText方法获取字符串显示出来。
                     */
                    options1Items = jsonBean;
                    for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
                        ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
                        ArrayList<String> codeList = new ArrayList<>();//该省的城市编码列表
                        for (int c = 0; c < jsonBean.get(i).getChildren().size(); c++) {
                            //遍历该省份的所有城市
                            String CityName = jsonBean.get(i).getChildren().get(c).getLabel();
                            String code = jsonBean.get(i).getChildren().get(c).getValue() + "";
                            CityList.add(CityName);//添加城市
                            codeList.add(code);
                        }
                        /**
                         * 添加城市数据
                         */
                        options2Items.add(CityList);
                        CodeList.add(codeList);
                    }
                    e.onNext(true);
                } else {
                    e.onNext(true);
                }

            }
        }).compose(RxSchedulers.<Boolean>lifecycle(activity)).subscribe(new MyObserver<Boolean>() {
            @Override
            public void onNext(Boolean value) {
                super.onNext(value);
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, View v) {
                        //返回的分别是三个级别的选中位置
                        String tx = options1Items.get(options1).getPickerViewText();
                        if (options2Items.get(options1).size() > 0) {
                            tx += options2Items.get(options1).get(options2);
                            //城市代码
                            personInterface.setCityCode(CodeList.get(options1).get(options2));
                        } else {
                            //省代码
                            personInterface.setCityCode(options1Items.get(options1).getValue() + "");
                        }
                        tv_area.setText(tx);

                    }
                })
                        .setTitleText("城市选择")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .setOutSideCancelable(false)// default is true
                        .build();
                pvOptions.setPicker(options1Items, options2Items);
                pvOptions.wheelOptions.setCurrentItems(13, 0, 0);
                pvOptions.show();
            }
        });


    }

     ArrayList<CityBean> parseData(String result) {
        //Gson 解析
        ArrayList<CityBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                Log.i("i", data.optJSONObject(i).toString());
                CityBean entity = gson.fromJson(data.optJSONObject(i).toString(), CityBean.class);
                detail.add(entity);
            }
            first = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    public void saveMessage(String value, final String nickName) {
        Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().changeProfile(DataSign.getSign(value, activity));
        observable.compose(RxSchedulers.<BaseEntity<Boolean>>lifecycle(activity))
        .compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                .subscribe(new BaseObserver<Boolean>(activity) {
                    @Override
                    public void onSuccess(Boolean response) {
                        MyUtils.showToast(activity, "修改信息成功");
                        SharedPreferencesUtils.changeUserName(nickName, activity);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        MyUtils.showToast(activity, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(activity, msg);

                    }
                });
    }

    public interface PersonInterface {
        void setMessage(PersonBean personBean);

        void getMessageFail(String msg);

        void setCityCode(String code);
    }
}
